import { useState, useCallback } from 'react';
import type { Socket } from 'socket.io-client';

/**
 * WebRTC连接管理Hook
 * @param socket - Socket.io客户端实例
 * @returns WebRTC相关状态和方法
 */
export const useWebRTC = (socket: Socket) => {
  const [peerConnections, setPeerConnections] = useState<Map<string, RTCPeerConnection>>(new Map());

  /**
   * 初始化RTCPeerConnection
   * @returns 新创建的RTCPeerConnection实例
   */
  const initPeerConnection = useCallback((userId?: string) => {
    const pc = new RTCPeerConnection({
      iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' },
        { urls: 'stun:stun01.sipphone.com' },
        { urls: 'stun:stun.ekiga.net' },
        { urls: 'stun:stun.fwdnet.net' },
        { urls: 'stun:stun.ideasip.com' },
        { urls: 'stun:stun.iptel.org' },
        { urls: 'stun:stun.rixtelecom.se' },
        { urls: 'stun:stun.schlund.de' },
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' },
        { urls: 'stun:stun2.l.google.com:19302' },
        { urls: 'stun:stun3.l.google.com:19302' },
        { urls: 'stun:stun4.l.google.com:19302' },
        { urls: 'stun:stunserver.org' },
        { urls: 'stun:stun.softjoys.com' },
        { urls: 'stun:stun.voiparound.com' },
        { urls: 'stun:stun.voipbuster.com' },
        { urls: 'stun:stun.voipstunt.com' },
        { urls: 'stun:stun.voxgratia.org' },
        { urls: 'stun:stun.xten.com' },
        {
          urls: 'turn:numb.viagenie.ca',
          credential: 'muazkh',
          username: 'webrtc@live.com'
        },
        {
          urls: 'turn:192.158.29.39:3478?transport=udp',
          credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
          username: '28224511:1379330808'
        },
        {
          urls: 'turn:192.158.29.39:3478?transport=tcp',
          credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
          username: '28224511:1379330808'
        }
      ],
    });

    // 监听并发送ICE候选
    pc.onicecandidate = (event) => {
      if (event.candidate) {
        console.log(`发送 ICE candidate 到 ${userId}`);
        socket.emit('ice-candidate', {
          candidate: event.candidate,
          userId: socket.id,
          targetUserId: userId
        });
      }
    };

    pc.onconnectionstatechange = () => {
      console.log(`连接状态 (${userId}):`, pc.connectionState);
      if (pc.connectionState === 'failed') {
        console.log('连接失败，尝试重新建立连接');
        pc.restartIce();
      }
    };

    pc.oniceconnectionstatechange = () => {
      console.log(`ICE状态 (${userId}):`, pc.iceConnectionState);
    };

    return pc;
  }, [socket]);

  return {
    peerConnections,
    setPeerConnections,
    initPeerConnection,
  };
};
